package com.experiment.experiment_big.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.experiment.experiment_big.entity.DangerRegion;
import com.experiment.experiment_big.entity.EpidmicData;
import com.experiment.experiment_big.entity.User;
import com.experiment.experiment_big.entity.vo.Clock_Data;
import com.experiment.experiment_big.entity.vo.Clock_inf;
import com.experiment.experiment_big.entity.vo.Data_multiple;
import com.experiment.experiment_big.service.DangerRegionService;
import com.experiment.experiment_big.service.EpidmicDataService;
import com.experiment.experiment_big.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-06-13
 */
@Controller
public class EpidmicDataController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private EpidmicDataService epidmicDataService;

    @Autowired
    private DangerRegionService dangerRegionService;

    /**
     * 用户打卡
     * @param clock_inf
     * @param model
     * @return
     */
    @RequestMapping("/submitform")
    public String submit_form(Clock_inf clock_inf, Model model){
        String id = clock_inf.getUserId();
        //设置用户数据数据
        EpidmicData epidmicData = new EpidmicData();
        epidmicData.setUserId(id);
        epidmicData.setAddress(clock_inf.getDayAddress());
        BigDecimal bigDecimal = new BigDecimal(clock_inf.getTemperature());
        epidmicData.setTemperature(bigDecimal);
        Date date = new Date();
        epidmicData.setFillingDate(date);
        //获取用户，主要是为了获取用户表单提交时间
        User user2 = userService.getById(id);
        //获得last_punch_time
        Date last_punch_time = user2.getLastPunchTime();
        // 当前时间
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //获取今天的日期
        String nowDay = sf.format(now);
        //对比的时间
        String day = sf.format(last_punch_time);
        //判断用户今天是否提交过
        boolean form_clock = true;
        if(nowDay.equals(day)){
            //已提交
            form_clock = false;

        }else{
            form_clock = true;
            //未提交
        }

        boolean fate = true;
        //如果用户为提交，提交数据
        if(form_clock){
            try {
                fate = epidmicDataService.save(epidmicData);
                if(fate = true){
                    User user = userService.getById(id);
                    //打卡天数增加
                    int count = user.getConsecutiveDay();
                    count++;
                    user.setConsecutiveDay(count);
                    //更新日期
                    user.setLastPunchTime(date);
                    userService.updateById(user);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        User user1 = userService.getById(id);
        model.addAttribute("user",user1);

        model.addAttribute("if_clo",false);


        return "submit_form";
    }

    //管理员打卡
    @RequestMapping("/admin_clock")
    public String admin_clock(Model model){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        org.springframework.security.core.userdetails.User principal1 =(org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        String id = principal1.getUsername();
        //查出用户信息
        com.experiment.experiment_big.entity.User byId = userService.getById(id);
        model.addAttribute("user",byId);//用户信息

        //获得last_punch_time
        Date last_punch_time = byId.getLastPunchTime();
        // 当前时间
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //获取今天的日期
        String nowDay = sf.format(now);
        //对比的时间
        String day = sf.format(last_punch_time);

        if(nowDay.equals(day)){
            //隐藏提交按钮
            model.addAttribute("if_clo",false);

        }else{
            model.addAttribute("if_clo",true);
            //今天未提交
        }
        List<DangerRegion> dangerRegionList = new ArrayList<>();
        dangerRegionList = dangerRegionService.list(null);
        List<DangerRegion> highdangerRegionList = new ArrayList<>();
        List<DangerRegion> zhongdangerRegionList = new ArrayList<>();
        for(DangerRegion dangerRegion:dangerRegionList){
            if(dangerRegion.getDangerLevel()==2){
                zhongdangerRegionList.add(dangerRegion);
            }else if(dangerRegion.getDangerLevel()==3){
                highdangerRegionList.add(dangerRegion);
            }
        }
        System.out.println(highdangerRegionList);
        System.out.println(zhongdangerRegionList);
        model.addAttribute("high",highdangerRegionList);
        model.addAttribute("zhong",zhongdangerRegionList);
        return "submit_form";
    }

    /**
     * 获得所有用户今日的打卡数据
     * @return
     */
    @RequestMapping("/punch_in_record")
    public String no_clock_in(Model model){

        Date dang = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取今天的日期
        String nowDay = sdf.format(dang);
        QueryWrapper<EpidmicData> epidmicDataWrapper = new QueryWrapper<>();
        epidmicDataWrapper.apply("date_format(filling_date,'%Y-%m-%d') = {0}",nowDay);
        List<EpidmicData> list = epidmicDataService.list(epidmicDataWrapper);
        System.out.println(list);
        List<Clock_Data> clock_datas = new ArrayList<>();

        for(EpidmicData e:list){
            Clock_Data clock_data = new Clock_Data();
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            clock_data.setAddress(e.getAddress());
            clock_data.setFillingDate(e.getFillingDate());
            clock_data.setTemperature(e.getTemperature());
            clock_data.setUserId(e.getUserId());

            User user = userService.getById(e.getUserId());
            clock_data.setUsername(user.getUserName());
            clock_datas.add(clock_data);

        }
        model.addAttribute("clock_data",clock_datas);
        return "punch_in_record";
    }


    /**
     * 多条件收索
     * @return
     */
    @RequestMapping("/data_multiple")
    public String data_multiple(Data_multiple data_multiple, Model model, String excel, HttpServletResponse response) throws IOException {
        QueryWrapper<EpidmicData> epidmicWrapper = new QueryWrapper<>();
        //如果学号不为空
        if(!data_multiple.getUser_id().equals("")){
            epidmicWrapper.eq("user_id",data_multiple.getUser_id());
        }
        if(data_multiple.getStart_time()!=null){
            Date dang = data_multiple.getStart_time();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //获取今天的日期
            String nowDay = sdf.format(dang);
            //查询条件为时间范围

            epidmicWrapper.apply("date_format(filling_date,'%Y-%m-%d') = {0}",nowDay);
        }
        if(data_multiple.getTemperature()!=null){
            epidmicWrapper.ge("temperature",data_multiple.getTemperature());
        }
        List<EpidmicData> list= epidmicDataService.list(epidmicWrapper);

        List<Clock_Data> clock_datas = new ArrayList<>();

        for(EpidmicData e:list){
            Clock_Data clock_data = new Clock_Data();
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            clock_data.setAddress(e.getAddress());
            clock_data.setFillingDate(e.getFillingDate());
            clock_data.setTemperature(e.getTemperature());
            clock_data.setUserId(e.getUserId());

            User user = userService.getById(e.getUserId());
            clock_data.setUsername(user.getUserName());
            clock_datas.add(clock_data);

        }
        if(excel!=null){
            ServletOutputStream out = out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            String filename = "打卡记录";
            writer.write(clock_datas,new WriteSheet());
            //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
            response.setHeader("Content-disposition", "attachment;filename=" + new String( filename.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
            writer.finish();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            out.flush();
        }
        model.addAttribute("clock_data",clock_datas);
        return "punch_in_record";
    }
}

